import 'package:app/api/inventory/index.dart';
import 'package:app/api/qrcode/index.dart';
import 'package:app/components/index.dart';
import 'package:app/util/StringUtils.dart';
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;

class Station extends StatefulWidget{

  const Station({super.key});

  @override
  State<Station> createState() => _StationState();
}

class _StationState extends State<Station>{

  String _code = "";
  // 站点码
  String _stationCode = "";
  // 托盘码
  String _containerCode = "";

  bool _isStation = true;

  bool _isContainer = true;

  final FocusNode _stationFocusNode = FocusNode();

  final FocusNode _containerFocusNode = FocusNode();

  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setParam(ModalRoute.of(context)!.settings.arguments);
      QrcodeApi.of(context).valueByCode(_code).then((res){
        setState((){
          if(StringUtils.isNull(res.data['data'])){
            _isContainer = false;
            FocusScope.of(context).requestFocus(_stationFocusNode);
          }else{
            _isStation = false;
            FocusScope.of(context).requestFocus(_containerFocusNode);
          }
        });
      });
    });
  }

  setParam(params){
    setState((){
      _code = params['code'];
      _containerCode = params['containerCode']??'';
      _stationCode = params['stationCode']??'';
    });
  }

  void scan(String key) async{
    String? qrCode = await scanner.scan();
    if (key == 'stationCode') {
      setState(() => _stationCode = qrCode.toString());
    } else if (key == 'containerCode') {
      setState(() => _containerCode = qrCode.toString());
    }
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  /// 提交
  submit(){
    Forms.validate(_formKey!).then((valid){
      if(valid){
        InventoryApi.of(context).modifyStationOrContainer(
            {
              'stationCode': _stationCode,
              'containerCode': _containerCode,
              'isFlag': _isStation
            }
        ).then((res){
          if(res.data['code'] == 'success'){
            Success.of(context).show(_isStation ? '站点修改成功' : '托盘修改成功');
          }
        });
      }
    });
  }

  /// 删除站点或托盘
  void remove(String code ,String isFlag){
    Confirm.of(context).show(isFlag == '1' ? '确定要清空站点么？' : '确定要清空托盘么？', (){
      InventoryApi.of(context).removeStationOrContainer(code, isFlag).then((res){
        if(res.data['code'] == 'success'){
          Success.of(context).show(isFlag == '1' ? '站点已清空' : '托盘已清空');
          Navigator.pop(context);
        }
      });
    });
  }

  /// 设置值
  void setValue(key, value){
    switch(key){
      case '_containerCode' : setState(() => _containerCode = value); break;
      case '_stationCode': setState(()  => _stationCode = value); break;
      default:
        throw Exception("key error");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(
        context: context,
        title: '站点更新',
      ),
      body: GestureDetector(
        onTap: hideKeyBorder,
        child: Column(
          children: [
            Group(
              title: '站点托盘信息',
              child: Column(
                children: [
                  Forms(
                      formKey: _formKey,
                      formItem: [
                        FormItem(
                          // onEntry: (value)=>{submit('stationCode', value)},
                          type: 'input',
                          labelWidth: 90,
                          labelText: '站点编号',
                          focusNode: _stationFocusNode,
                          placeholder: '请扫描站点编号',
                          filedName: 'stationCode',
                          enabled: _isStation,
                          value: _stationCode,
                          onChange: (value) => setValue('_stationCode', value),
                          icon: const Icon(Icons.qr_code_scanner_rounded),
                          iconOnTap: () => scan('stationCode'),
                          rules: const {'stationCode': [{'required': true, 'message': '站点编号不能为空'}]},
                        ),
                        FormItem(
                          // onEntry: (value)=>{submit('containerCode', value)},
                          type: 'input',
                          labelWidth: 90,
                          focusNode: _containerFocusNode,
                          labelText: '托盘编号',
                          placeholder: '请扫描托盘编号',
                          filedName: 'containerCode',
                          enabled: _isContainer,
                          value: _containerCode,
                          onChange: (value) => setValue('_containerCode', value),
                          icon: const Icon(Icons.qr_code_scanner_rounded),
                          iconOnTap: () => scan('containerCode'),
                          rules: const {'containerCode': [{'required': true, 'message': '托盘编号不能为空'}]},
                        ),
                      ]
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 10, right: 10, bottom: 10),
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Padding(
                              padding: const EdgeInsets.only(right: 10),
                            child: Button(
                              label: '清空站点',
                              icon: Icons.delete_forever,
                              iconColor: Colors.white,
                              onPressed: ()=>{remove(_stationCode, "1")},
                              fontColor: Colors.white,
                              backgroundColor: Colors.green,
                              borderColor: Colors.green,
                            ),
                          ),
                          Button(
                            label: '清空托盘',
                            icon: Icons.delete_forever,
                            onPressed: ()=>{remove(_containerCode, "0")},
                            iconColor: Colors.white,
                            backgroundColor: Colors.lightBlue,
                            borderColor: Colors.lightBlue,
                          ),
                        ]
                    ),
                  ),
                  SizedBox(
                    width: MediaQuery
                        .of(context)
                        .size
                        .width,
                    child: Padding(
                      padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
                      child: Button(
                        onPressed: submit,
                        label: _isStation ? '更新站点' : '更新托盘',
                        height: 60,
                        fontSize: 18,
                      ),
                    ),
                  ),
                ],
              )
            ),
          ],
        )
      )
    );
  }

}